var express = require('express');
var router = express.Router();
// 连接数据库，引入集合
const pro = require("../sql/pro")
// 引入数据操作工具库
const sql = require("../sql/sql")

// 生成唯一商品id模块
const uuid = require("uuid")

// 初始表格路由（获取数据并渲染页面模板路由）
router.get('/', function(req, res, next) {
  sql.get(pro).then((data)=>{
    // console.log(data)
    res.render('pro', {
      index: 1,
      data
    });
  })
});

// 修改的页面模板路由
router.get('/add', function(req, res, next) {
  res.render('addForm', {
    index: 1
  });
});

// 修改的功能路由
router.post('/addAction', function(req, res, next) {
  // 先拿到数据
  // console.log(req.body);
  let data = req.body;
  data.price = Number(data.price);
  data.sales = data.sales-0;
  data.stock = data.stock*1;
  data.score = data.score/1;
  data.discount = data.discount/1;
  data.proId = "proId-" + uuid.v1();
  data.time = Date.now()

  // 插入数据
  sql.add(pro, req.body).then(()=>{
    // 成功之后，回到表格页面模板，显示最新数据
    // res.send("添加 ok")
    res.redirect("/pro")
  })
});

// 删除的功能路由
router.get('/del', function(req, res, next) {
  // console.log(req.query)
  let id = req.query.id;

  sql.remove(pro, {proId:id}).then(()=>{
    res.redirect("/pro")
  })
});


// 修改的页面模板路由
router.get('/update', function(req, res, next) {
  let id = req.query.id;

  sql.get(pro, {proId:id}).then(data=>{
    res.render('updateForm', {
      index: 1,
      data: data[0]
    });
  })

});

// 修改的功能路由
router.post('/updateAction', function(req, res, next) {
  let data = req.body;

  data.price = Number(data.price);
  data.sales = data.sales-0;
  data.stock = data.stock*1;
  data.score = data.score/1;
  data.discount = data.discount/1;

  sql.set(pro, {proId:data.proId}, {$set:data}).then(()=>{
    res.redirect("/pro")
  })

});

module.exports = router;
